/**
 * 实训任务四 - 数据表格JavaScript
 * 支持过滤、排序、分页功能
 */

// 全局变量
let currentPage = 1;
let pageSize = 10;
let currentSort = [];
let currentFilters = [];
let totalPages = 0;
let totalCount = 0;
let multipleFiltersEnabled = false;
let deleteRecordId = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeEventListeners();
    loadData();
});

/**
 * 初始化事件监听器
 */
function initializeEventListeners() {
    // 排序事件
    document.querySelectorAll('.sortable').forEach(th => {
        th.addEventListener('click', function() {
            handleSort(this.dataset.column);
        });
    });

    // 过滤操作符变化事件
    document.getElementById('filterOperator').addEventListener('change', function() {
        toggleFilterValue2();
    });

    // 回车键应用过滤
    document.getElementById('filterValue').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            applyFilter();
        }
    });

    document.getElementById('filterValue2').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            applyFilter();
        }
    });

    // 页面跳转回车键事件
    document.getElementById('pageJumpInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            jumpToPage();
        }
    });

    // 模态框点击外部关闭
    document.getElementById('recordModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeModal();
        }
    });

    document.getElementById('deleteModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeDeleteModal();
        }
    });
}

/**
 * 处理排序
 */
function handleSort(column) {
    // 查找当前列的排序状态
    let existingSort = currentSort.find(s => s.column === column);
    
    if (existingSort) {
        // 切换排序方向
        if (existingSort.direction === 'ASC') {
            existingSort.direction = 'DESC';
        } else {
            // 移除排序
            currentSort = currentSort.filter(s => s.column !== column);
        }
    } else {
        // 添加新排序（如果不是多重排序，清除其他排序）
        if (!event.ctrlKey && !event.metaKey) {
            currentSort = [];
        }
        currentSort.push({
            column: column,
            direction: 'ASC',
            priority: currentSort.length + 1
        });
    }
    
    updateSortHeaders();
    currentPage = 1; // 重置到第一页
    loadData();
}

/**
 * 更新排序表头显示
 */
function updateSortHeaders() {
    // 清除所有排序样式
    document.querySelectorAll('.sortable').forEach(th => {
        th.classList.remove('sort-asc', 'sort-desc');
    });
    
    // 应用当前排序样式
    currentSort.forEach(sort => {
        const th = document.querySelector(`[data-column="${sort.column}"]`);
        if (th) {
            th.classList.add(sort.direction === 'ASC' ? 'sort-asc' : 'sort-desc');
        }
    });
}

/**
 * 应用过滤
 */
function applyFilter() {
    const column = document.getElementById('filterColumn').value;
    const operator = document.getElementById('filterOperator').value;
    const value = document.getElementById('filterValue').value;
    const value2 = document.getElementById('filterValue2').value;

    if (!column || !value) {
        showError('请选择过滤字段并输入过滤值');
        return;
    }

    // 如果启用了多重过滤，则不清空现有过滤条件
    if (!multipleFiltersEnabled) {
        currentFilters = [];
    }

    // 构建过滤条件
    if (operator === 'BETWEEN' && value2) {
        currentFilters.push({
            column: column,
            operator: operator,
            value: value,
            value2: value2
        });
    } else {
        currentFilters.push({
            column: column,
            operator: operator,
            value: value
        });
    }

    currentPage = 1; // 重置到第一页
    loadData();
}

/**
 * 清除过滤
 */
function clearFilters() {
    document.getElementById('filterColumn').value = '';
    document.getElementById('filterValue').value = '';
    document.getElementById('filterValue2').value = '';
    document.getElementById('filterOperator').value = 'LIKE';
    toggleFilterValue2();
    
    currentFilters = [];
    currentPage = 1;
    loadData();
}

/**
 * 切换第二个过滤值的显示
 */
function toggleFilterValue2() {
    const operator = document.getElementById('filterOperator').value;
    const value2Input = document.getElementById('filterValue2');
    
    if (operator === 'BETWEEN') {
        value2Input.style.display = 'inline-block';
    } else {
        value2Input.style.display = 'none';
        value2Input.value = '';
    }
}

/**
 * 切换多重过滤器
 */
function toggleMultipleFilters() {
    multipleFiltersEnabled = !multipleFiltersEnabled;
    const multipleFiltersDiv = document.getElementById('multipleFilters');
    const singleFilterDiv = document.getElementById('singleFilter');
    const toggleButton = document.querySelector('button[onclick="toggleMultipleFilters()"]');

    if (multipleFiltersEnabled) {
        // 显示多重过滤器，隐藏单字段过滤器
        multipleFiltersDiv.style.display = 'block';
        singleFilterDiv.style.display = 'none';
        toggleButton.textContent = '切换单字段过滤';
        addFilter();
    } else {
        // 显示单字段过滤器，隐藏多重过滤器
        multipleFiltersDiv.style.display = 'none';
        singleFilterDiv.style.display = 'block';
        toggleButton.textContent = '切换多重过滤';
        clearMultipleFilters();
    }
}

/**
 * 添加过滤条件
 */
function addFilter() {
    const container = document.getElementById('filterContainer');
    const filterIndex = container.children.length + 1;
    
    const filterDiv = document.createElement('div');
    filterDiv.className = 'multiple-filter-item';
    filterDiv.innerHTML = `
        <div class="filter-row">
            <label>字段:</label>
            <select class="filter-column">
                <option value="">选择字段</option>
                <option value="id">ID</option>
                <option value="name">姓名</option>
                <option value="number">性别</option>
                <option value="price">身份信息</option>
                <option value="madetime">生日</option>
            </select>
            
            <label>操作:</label>
            <select class="filter-operator">
                <option value="LIKE">包含</option>
                <option value="=">=等于</option>
                <option value=">">大于</option>
                <option value="<">小于</option>
                <option value=">=">大于等于</option>
                <option value="<=">小于等于</option>
                <option value="BETWEEN">范围</option>
            </select>
            
            <label>值:</label>
            <input type="text" class="filter-value" placeholder="输入过滤值">
            <input type="text" class="filter-value2" placeholder="结束值" style="display:none;">
            
            <button class="remove-filter" onclick="removeFilter(this)">×</button>
        </div>
    `;
    
    container.appendChild(filterDiv);
    
    // 添加事件监听器
    const operatorSelect = filterDiv.querySelector('.filter-operator');
    operatorSelect.addEventListener('change', function() {
        const value2Input = filterDiv.querySelector('.filter-value2');
        if (this.value === 'BETWEEN') {
            value2Input.style.display = 'inline-block';
        } else {
            value2Input.style.display = 'none';
            value2Input.value = '';
        }
    });
}

/**
 * 移除过滤条件
 */
function removeFilter(button) {
    button.closest('.multiple-filter-item').remove();
}

/**
 * 清除多重过滤器
 */
function clearMultipleFilters() {
    document.getElementById('filterContainer').innerHTML = '';
}

/**
 * 应用多重过滤器
 */
function applyMultipleFilters() {
    const filterItems = document.querySelectorAll('.multiple-filter-item');
    currentFilters = [];
    
    filterItems.forEach(item => {
        const column = item.querySelector('.filter-column').value;
        const operator = item.querySelector('.filter-operator').value;
        const value = item.querySelector('.filter-value').value;
        const value2 = item.querySelector('.filter-value2').value;
        
        if (column && value) {
            if (operator === 'BETWEEN' && value2) {
                currentFilters.push({
                    column: column,
                    operator: operator,
                    value: value,
                    value2: value2
                });
            } else {
                currentFilters.push({
                    column: column,
                    operator: operator,
                    value: value
                });
            }
        }
    });
    
    currentPage = 1;
    loadData();
}

/**
 * 改变页面大小
 */
function changePageSize() {
    pageSize = parseInt(document.getElementById('pageSize').value);
    currentPage = 1;
    loadData();
}

/**
 * 跳转到指定页面
 */
function goToPage(page) {
    if (page >= 1 && page <= totalPages) {
        currentPage = page;
        loadData();
    }
}

/**
 * 上一页
 */
function previousPage() {
    if (currentPage > 1) {
        currentPage--;
        loadData();
    }
}

/**
 * 下一页
 */
function nextPage() {
    if (currentPage < totalPages) {
        currentPage++;
        loadData();
    }
}

/**
 * 跳转到指定页面
 */
function jumpToPage() {
    const pageInput = document.getElementById('pageJumpInput');
    const targetPage = parseInt(pageInput.value);

    if (isNaN(targetPage) || targetPage < 1 || targetPage > totalPages) {
        showError(`请输入有效的页码 (1-${totalPages})`);
        pageInput.value = '';
        return;
    }

    currentPage = targetPage;
    pageInput.value = '';
    loadData();
}

/**
 * 加载数据
 */
function loadData() {
    showLoading();
    
    // 构建请求参数
    const params = new URLSearchParams();
    params.append('page', currentPage);
    params.append('pageSize', pageSize);
    
    // 添加排序参数
    currentSort.forEach((sort, index) => {
        params.append(`sort${index + 1}Column`, sort.column);
        params.append(`sort${index + 1}Direction`, sort.direction);
    });
    
    // 添加过滤参数
    currentFilters.forEach((filter, index) => {
        params.append(`filter${index + 1}Column`, filter.column);
        params.append(`filter${index + 1}Operator`, filter.operator);
        params.append(`filter${index + 1}Value`, filter.value);
        if (filter.value2) {
            params.append(`filter${index + 1}Value2`, filter.value2);
        }
    });
    
    // 发送AJAX请求
    fetch('productDataTable?' + params.toString())
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayData(data);
                updatePagination(data);
                updateRecordInfo(data);
                hideError();
            } else {
                showError(data.message || '加载数据失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('网络错误，请稍后重试');
        })
        .finally(() => {
            hideLoading();
        });
}

/**
 * 显示数据
 */
function displayData(data) {
    const tbody = document.getElementById('tableBody');



    if (!data.data || data.data.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="empty-state">
                    <div class="empty-icon">📋</div>
                    <div class="empty-message">暂无数据</div>
                    <div class="empty-description">请尝试调整过滤条件</div>
                </td>
            </tr>
        `;
        return;
    }

    let html = '';
    data.data.forEach((record, index) => {
        html += `
            <tr>
                <td class="number-cell">${record.id}</td>
                <td>${escapeHtml(record.name)}</td>
                <td>${escapeHtml(record.number)}</td>
                <td>${escapeHtml(record.price)}</td>
                <td class="date-cell">${formatDate(record.madetime)}</td>
                <td class="action-buttons">
                    <button class="btn btn-warning btn-sm" onclick="goToEditPage(${record.id})">编辑</button>
                    <button class="btn btn-danger btn-sm" onclick="confirmDelete(${record.id}, '${escapeHtml(record.name).replace(/'/g, "\\'")}')">删除</button>
                </td>
            </tr>
        `;
    });

    tbody.innerHTML = html;
}



/**
 * 更新分页控件
 */
function updatePagination(data) {
    totalPages = data.totalPages;
    totalCount = data.totalCount;

    const pagination = document.getElementById('pagination');
    let html = '';

    // 上一页按钮
    html += `<button onclick="previousPage()" ${currentPage <= 1 ? 'disabled' : ''}>上一页</button>`;

    // 页码按钮
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);

    if (startPage > 1) {
        html += `<button onclick="goToPage(1)">1</button>`;
        if (startPage > 2) {
            html += `<span>...</span>`;
        }
    }

    for (let i = startPage; i <= endPage; i++) {
        html += `<button onclick="goToPage(${i})" ${i === currentPage ? 'class="current-page"' : ''}>${i}</button>`;
    }

    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            html += `<span>...</span>`;
        }
        html += `<button onclick="goToPage(${totalPages})">${totalPages}</button>`;
    }

    // 下一页按钮
    html += `<button onclick="nextPage()" ${currentPage >= totalPages ? 'disabled' : ''}>下一页</button>`;

    pagination.innerHTML = html;

    // 更新页面信息显示
    const pageInfo = document.getElementById('pageInfo');
    if (pageInfo) {
        pageInfo.innerHTML = `第 ${currentPage} 页，共 ${totalPages} 页`;
    }
}

/**
 * 更新记录信息
 */
function updateRecordInfo(data) {
    const recordInfo = document.getElementById('recordInfo');
    recordInfo.textContent = `总记录数: ${data.totalCount}，当前显示: ${data.data.length} 条`;

    // 更新页面跳转输入框的最大值
    const pageJumpInput = document.getElementById('pageJumpInput');
    pageJumpInput.max = data.totalPages;
    pageJumpInput.placeholder = `1-${data.totalPages}`;
}

/**
 * 显示加载状态
 */
function showLoading() {
    const tbody = document.getElementById('tableBody');
    tbody.innerHTML = '<tr><td colspan="6" class="loading">正在加载数据...</td></tr>';
}

/**
 * 隐藏加载状态
 */
function hideLoading() {
    // 加载状态会被实际数据替换，这里不需要特殊处理
}

/**
 * 显示错误信息
 */
function showError(message) {
    const errorDiv = document.getElementById('errorMessage');
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';

    // 3秒后自动隐藏
    setTimeout(() => {
        hideError();
    }, 3000);
}

/**
 * 隐藏错误信息
 */
function hideError() {
    const errorDiv = document.getElementById('errorMessage');
    errorDiv.style.display = 'none';
}

/**
 * HTML转义
 */
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

/**
 * 格式化日期时间
 */
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';

    try {
        const date = new Date(dateTimeStr);
        return date.getFullYear() + '-' +
               String(date.getMonth() + 1).padStart(2, '0') + '-' +
               String(date.getDate()).padStart(2, '0') + ' ' +
               String(date.getHours()).padStart(2, '0') + ':' +
               String(date.getMinutes()).padStart(2, '0') + ':' +
               String(date.getSeconds()).padStart(2, '0');
    } catch (e) {
        return dateTimeStr;
    }
}

/**
 * 格式化日期（仅日期部分）
 */
function formatDate(dateTimeStr) {
    if (!dateTimeStr) return '';

    try {
        const date = new Date(dateTimeStr);
        return date.getFullYear() + '-' +
               String(date.getMonth() + 1).padStart(2, '0') + '-' +
               String(date.getDate()).padStart(2, '0');
    } catch (e) {
        return dateTimeStr;
    }
}

/**
 * 导出数据（可选功能）
 */
function exportData() {
    // 构建导出URL
    const params = new URLSearchParams();
    params.append('export', 'true');

    // 添加当前过滤和排序参数
    currentSort.forEach((sort, index) => {
        params.append(`sort${index + 1}Column`, sort.column);
        params.append(`sort${index + 1}Direction`, sort.direction);
    });

    currentFilters.forEach((filter, index) => {
        params.append(`filter${index + 1}Column`, filter.column);
        params.append(`filter${index + 1}Operator`, filter.operator);
        params.append(`filter${index + 1}Value`, filter.value);
        if (filter.value2) {
            params.append(`filter${index + 1}Value2`, filter.value2);
        }
    });

    // 打开新窗口下载
    window.open('productDataTable?' + params.toString(), '_blank');
}

// ========== 页面跳转函数 ==========

/**
 * 跳转到数据管理页面
 */
function goToCrudPage() {
    window.location.href = 'crud.jsp';
}

/**
 * 跳转到添加页面
 */
function goToAddPage() {
    window.location.href = 'add.jsp';
}

/**
 * 跳转到编辑页面
 */
function goToEditPage(id) {
    window.location.href = 'edit.jsp?id=' + id;
}

/**
 * 确认删除
 */
function confirmDelete(id, name) {
    if (confirm(`确定要删除 "${name}" 吗？`)) {
        deleteRecord(id);
    }
}

/**
 * 删除记录
 */
function deleteRecord(id) {
    fetch('/wanlang/shixun4/api/delete?id=' + id, {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showError('删除成功！');
            setTimeout(() => {
                loadData();
            }, 1000);
        } else {
            showError(data.message || '删除失败');
        }
    })
    .catch(error => {
        showError('删除失败：' + error.message);
    });
}
